<script setup lang="ts">
// 引入Element Plus图标
import {
  Briefcase,
  Calendar,
  Check,
  DocumentChecked,
  HomeFilled,
  InfoFilled,
  OfficeBuilding,
  User
} from "@element-plus/icons-vue"
import { ElMessage } from "element-plus"
import { computed, ref, watch } from "vue"
import { usePositionTeacherStore } from "@/pinia/stores/position-teacher"

const props = defineProps<{
  modelValue: boolean
  positionId?: number
}>()

const emit = defineEmits<{
  "update:modelValue": [value: boolean]
  "close": []
}>()

const positionStore = usePositionTeacherStore()
const loading = ref(false)
const visible = ref(props.modelValue)

// 直接从store计算获取职位详情
const positionDetail = computed(() => positionStore.positionDetail)

// 通过率、录取率
const passRate = computed(() => {
  if (!positionDetail.value?.applyCount || positionDetail.value.applyCount === 0) return "0%"
  const rate = ((positionDetail.value.passCount || 0) / positionDetail.value.applyCount) * 100
  return `${rate.toFixed(1)}%`
})

const admissionRate = computed(() => {
  if (!positionDetail.value?.applyCount || positionDetail.value.applyCount === 0) return "0%"
  const rate = ((positionDetail.value.admissionCount || 0) / positionDetail.value.applyCount) * 100
  return `${rate.toFixed(1)}%`
})

// 加载职位详情
async function loadPositionDetail() {
  if (props.positionId === undefined || props.positionId === null || Number.isNaN(Number(props.positionId)) || Number(props.positionId) <= 0) {
    console.warn("无效的职位ID:", props.positionId)
    ElMessage.warning("无效的职位ID")
    return
  }

  loading.value = true
  try {
    const positionId = Number(props.positionId)

    const result = await positionStore.fetchPositionDetail(positionId)

    if (result) {
      console.log("职位详情加载成功:", result.positionName)
    } else {
      console.warn("职位详情加载失败，返回结果为null")
      ElMessage.warning("加载职位详情失败")
    }
  } catch (error) {
    console.error("加载职位详情失败:", error)
    ElMessage.error("加载职位详情失败")
  } finally {
    loading.value = false
  }
}

// 关闭弹窗时清除store中的详情数据
function handleClose() {
  emit("update:modelValue", false)
  emit("close")
  // 关闭时清除详情，避免数据残留
  setTimeout(() => {
    positionStore.resetPositionDetail()
  }, 300)
}

// 监听modelValue变化，更新本地visible变量
watch(() => props.modelValue, (newValue) => {
  visible.value = newValue
})

// 监听弹窗显示状态变化
watch(() => props.modelValue, (newValue) => {
  visible.value = newValue

  if (newValue && props.positionId && props.positionId > 0) {
    // 弹窗打开且有有效职位ID时加载数据
    loadPositionDetail()
  } else if (!newValue) {
    // 弹窗关闭时清除数据
    positionStore.resetPositionDetail()
  }
}, { immediate: true })

// 监听职位ID变化
watch(() => props.positionId, (newPositionId, oldPositionId) => {
  if (visible.value && newPositionId && newPositionId > 0 && newPositionId !== oldPositionId) {
    loadPositionDetail()
  }
})
</script>

<template>
  <el-dialog
    v-model="visible"
    :title="positionDetail ? `${positionDetail.positionName} - 职位详情` : '职位详情'"
    width="1200px"
    :loading="loading || positionStore.isLoadingDetail"
    @close="handleClose"
    class="position-detail-dialog"
  >
    <div v-if="positionDetail" class="position-detail-container">
      <!-- 职位头部信息卡片 -->
      <div class="position-header-card">
        <div class="position-logo">
          <el-avatar
            :size="80"
            :icon="Briefcase"
            class="position-avatar"
          />
        </div>
        <div class="position-header-info">
          <h2 class="position-name">
            {{ positionDetail.positionName }}
          </h2>
          <div class="position-meta">
            <span class="position-meta-item" v-if="positionDetail.companyName">
              <el-icon size="14"><OfficeBuilding /></el-icon> {{ positionDetail.companyName }}
            </span>
            <span class="position-meta-item">
              <el-tag :type="positionDetail.status === '招聘中' ? 'success' : 'warning'" size="small">
                <el-icon size="12"><Check /></el-icon> {{ positionDetail.status }}
              </el-tag>
            </span>
            <span class="position-meta-item">
              <el-icon size="14"><HomeFilled /></el-icon> {{ positionDetail.workCity || '-' }}
            </span>
            <span class="position-meta-item">
              <el-icon size="14"><Calendar /></el-icon> {{ positionDetail.salary || '-' }}
            </span>
          </div>
          <!-- 职位标签 -->
          <div v-if="positionDetail.tags && positionDetail.tags.length > 0" class="position-tags compact">
            <el-tag
              v-for="tag in positionDetail.tags"
              :key="tag"
              type="info"
              effect="plain"
              size="small"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>
      </div>

      <!-- 第一列：基本信息、职位要求 -->
      <div class="column-1">
        <!-- 基本信息 -->
        <div class="detail-card">
          <h3 class="card-title">
            <el-icon><InfoFilled /></el-icon>
            基本信息
          </h3>
          <div class="info-grid dense">
            <div class="info-item">
              <el-icon size="14">
                <HomeFilled />
              </el-icon>
              <span class="info-label">工作城市:</span>
              <el-tag type="info" effect="plain" size="small" class="info-tag">
                {{ positionDetail.workCity || '-' }}
              </el-tag>
            </div>
            <div class="info-item">
              <el-icon size="14">
                <Calendar />
              </el-icon>
              <span class="info-label">薪资范围:</span>
              <el-tag type="info" effect="plain" size="small" class="info-tag">
                {{ positionDetail.salary || '-' }}
              </el-tag>
            </div>
            <div class="info-item">
              <el-icon size="14">
                <User />
              </el-icon>
              <span class="info-label">招聘人数:</span>
              <span class="info-value">{{ positionDetail.recruitNum || 0 }}人</span>
            </div>
            <div class="info-item">
              <el-icon size="14">
                <Calendar />
              </el-icon>
              <span class="info-label">工作类型:</span>
              <el-tag type="info" effect="plain" size="small" class="info-tag">
                {{ positionDetail.workType || '-' }}
              </el-tag>
            </div>
          </div>
        </div>

        <!-- 职位要求 -->
        <div class="detail-card">
          <h3 class="card-title">
            <el-icon><DocumentChecked /></el-icon>
            职位要求
          </h3>
          <div class="position-requirement-text">
            {{ positionDetail.positionRequire || '暂无职位要求信息' }}
          </div>
        </div>
      </div>

      <!-- 第二列：申请统计、职位描述 -->
      <div class="column-2">
        <!-- 申请统计 -->
        <div class="detail-card">
          <h3 class="card-title">
            <el-icon><User /></el-icon>
            申请统计
          </h3>
          <div class="info-grid dense">
            <div class="info-item">
              <User class="info-icon" />
              <span class="info-label">申请人数:</span>
              <span class="info-value">{{ positionDetail.applyCount || 0 }}人</span>
            </div>
            <div class="info-item">
              <Check class="info-icon" />
              <span class="info-label">通过人数:</span>
              <span class="info-value">{{ positionDetail.passCount || 0 }}人</span>
            </div>
            <div class="info-item">
              <Check class="info-icon" />
              <span class="info-label">录取人数:</span>
              <span class="info-value">{{ positionDetail.admissionCount || 0 }}人</span>
            </div>
            <div class="info-item">
              <Calendar class="info-icon" />
              <span class="info-label">通过率:</span>
              <span class="info-value">{{ passRate }}</span>
            </div>
            <div class="info-item">
              <Calendar class="info-icon" />
              <span class="info-label">录取率:</span>
              <span class="info-value">{{ admissionRate }}</span>
            </div>
          </div>
        </div>

        <!-- 职位描述 -->
        <div class="detail-card">
          <h3 class="card-title">
            <el-icon><InfoFilled /></el-icon>
            职位描述
          </h3>
          <div class="position-description-text">
            {{ positionDetail.positionDesc || '暂无职位描述信息' }}
          </div>
        </div>
      </div>

      <!-- 第三列：公司信息、发布时间 -->
      <div class="column-3">
        <!-- 公司信息 -->
        <div class="detail-card">
          <h3 class="card-title">
            <el-icon><OfficeBuilding /></el-icon>
            公司信息
          </h3>
          <div class="info-grid dense">
            <div class="info-item full-width">
              <OfficeBuilding class="info-icon" />
              <span class="info-label">公司名称:</span>
              <span class="info-value">{{ positionDetail.companyName || '-' }}</span>
            </div>
            <div class="info-item full-width">
              <HomeFilled class="info-icon" />
              <span class="info-label">工作地址:</span>
              <span class="info-value">{{ positionDetail.workPlace || '-' }}</span>
            </div>
          </div>
        </div>

        <!-- 发布时间 -->
        <div class="detail-card">
          <h3 class="card-title">
            <el-icon><Calendar /></el-icon>
            时间信息
          </h3>
          <div class="info-grid dense">
            <div class="info-item full-width">
              <Calendar class="info-icon" />
              <span class="info-label">发布时间:</span>
              <span class="info-value">{{ positionDetail.publishTime || '-' }}</span>
            </div>
            <div class="info-item full-width">
              <Calendar class="info-icon" />
              <span class="info-label">截止时间:</span>
              <span class="info-value">{{ positionDetail.deadline || '-' }}</span>
            </div>
            <div class="info-item full-width">
              <User class="info-icon" />
              <span class="info-label">发布人:</span>
              <span class="info-value">{{ positionDetail.publishUserName || '-' }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 无数据时的占位显示 -->
    <div v-else-if="!loading && !positionStore.isLoadingDetail" class="empty-state">
      <el-empty description="暂无职位信息" :image-size="200" />
    </div>

    <template #footer>
      <el-button @click="handleClose" class="close-button">
        关闭
      </el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
:deep(.el-dialog) {
  .el-dialog__header {
    background: #f8f9fa;
    padding: 20px 25px;
    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }
  }

  .el-dialog__body {
    padding: 25px;
    max-height: none; /* 移除最大高度限制 */
    overflow-y: visible; /* 移除滚动条 */
  }

  /* 当第三列不存在时，减小弹窗宽度 */
  &:has(.position-detail-container:not(:has(.column-3))) {
    width: 800px !important;
  }
}

.position-detail-dialog {
  .el-dialog__footer {
    padding: 15px 25px 20px;
    border-top: 1px solid #ebeef5;
  }
}

.position-detail-container {
  display: grid;
  grid-template-columns: 1fr 1fr 350px;
  grid-template-rows: auto 1fr;
  gap: 16px;
  /* 确保所有列的高度一致 */

  /* 布局区域 */
  .position-header-card {
    grid-column: 1 / -1;
  }

  .column-1 {
    grid-column: 1;
    grid-row: 2;
    display: flex;
    flex-direction: column;
    gap: 16px;
    min-height: 0; /* 确保flex子元素可以收缩 */
    height: 100%; /* 确保列高与第三列一致 */
  }

  .column-2 {
    grid-column: 2;
    grid-row: 2;
    display: flex;
    flex-direction: column;
    gap: 16px;
    min-height: 0; /* 确保flex子元素可以收缩 */
    height: 100%; /* 确保列高与第三列一致 */
  }

  .column-3 {
    grid-column: 3;
    grid-row: 2;
    /* 第三列占两行 */
    display: flex;
    flex-direction: column;
    height: 100%; /* 确保列高固定 */
  }

  /* 当第三列不存在时，调整前两列布局 */
  &:not(:has(.column-3)) {
    grid-template-columns: 1fr 1fr;
  }
}

.position-header-card {
  display: flex;
  align-items: center;
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px 25px;
  color: #303133;
  border: 1px solid #e9ecef;
  margin-bottom: 16px;
}

.position-logo {
  margin-right: 24px;
}

.position-avatar {
  background: #e6f7ff;
  color: #1890ff;
  font-size: 36px;
  border: 1px solid #91d5ff;
}

.position-header-info {
  flex: 1;
}

.position-name {
  font-size: 20px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #303133;
}

.position-meta {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.position-meta-item {
  font-size: 14px;

  .meta-icon {
    margin-right: 4px;
    vertical-align: middle;
  }

  .tag-icon {
    margin-right: 2px;
  }
}

.detail-card {
  background: white;
  border-radius: 6px;
  padding: 14px 18px;
  border: 1px solid #e9ecef;
  margin-bottom: 0;
  display: flex;
  flex-direction: column;
  flex-grow: 1; /* 让卡片占满剩余空间 */
  min-height: 0; /* 确保内容溢出时可以收缩 */
  flex-shrink: 1; /* 允许卡片收缩 */
}

.card-title {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 12px 0;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f2f5;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  flex-grow: 1; /* 让信息网格占满剩余空间 */
  min-height: 0; /* 确保内容溢出时可以收缩 */

  &.dense {
    gap: 12px;
  }
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;

  &.full-width {
    grid-column: 1 / -1;
  }

  .info-icon {
    width: 16px;
    height: 16px;
    color: #6c757d;
  }

  .info-tag {
    margin-left: auto;
  }
}

.info-label {
  font-size: 14px;
  font-weight: 500;
  color: #6c757d;
  flex-shrink: 0;
  width: 80px;
}

.info-value {
  font-size: 14px;
  color: #212529;
  line-height: 1.5;
  word-break: break-all;
  flex: 1;
}

.position-requirement-text,
.position-description-text {
  background: #f8f9fa;
  border-radius: 4px;
  padding: 16px;
  font-size: 14px;
  line-height: 1.7;
  color: #495057;
  white-space: pre-wrap;
  border-left: 3px solid #17a2b8;
  min-height: 100px;
  flex-grow: 1; /* 让文本区域占满剩余空间 */
  overflow-y: auto; /* 当内容过多时可以滚动 */
}

.position-description-text {
  border-left-color: #28a745;
}

/* 标签样式已移至职位头部信息卡片内 */

.position-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 6px 0;

  &.compact {
    gap: 6px;
    padding: 4px 0;
  }
}

.close-button {
  min-width: 80px;
  transition: all 0.3s ease;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
  color: #6c757d;
}

@media (max-width: 1280px) {
  .el-dialog {
    width: 98% !important;
    margin: 0 auto;

    /* 当第三列不存在时，在小屏幕上减小最大宽度 */
    &:has(.position-detail-container:not(:has(.column-3))) {
      width: 90% !important;
      max-width: 700px;
    }
  }

  .position-detail-container {
    grid-template-columns: 1fr 1fr 300px;

    /* 当第三列不存在时的布局调整 */
    &:not(:has(.column-3)) {
      grid-template-columns: 1fr 1fr;
    }
  }
}

@media (max-width: 1024px) {
  .position-detail-container {
    grid-template-columns: 1fr 1fr;
    grid-template-rows: auto auto auto;

    .column-1 {
      grid-column: 1;
      grid-row: 2;
    }

    .column-2 {
      grid-column: 2;
      grid-row: 2;
    }

    .column-3 {
      grid-column: 1 / -1;
      grid-row: 3;
    }
  }
}

@media (max-width: 768px) {
  .position-detail-container {
    grid-template-columns: 1fr;
    grid-template-rows: auto auto auto auto;

    .column-1,
    .column-2,
    .column-3 {
      grid-column: 1;
    }

    .column-1 {
      grid-row: 2;
    }

    .column-2 {
      grid-row: 3;
    }

    .column-3 {
      grid-row: 4;
    }
  }

  .info-grid {
    grid-template-columns: 1fr;
  }

  .info-item {
    flex-direction: column;
  }

  .info-label {
    width: auto;
  }
}

@media (max-width: 768px) {
  .position-header-card {
    flex-direction: column;
    text-align: center;
    gap: 16px;
  }

  .info-grid {
    grid-template-columns: 1fr;
  }

  .info-item {
    flex-wrap: wrap;
  }

  .position-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}
</style>
